package com.zx.framework.core.util.gson;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.zx.framework.core.exception.DateFormatException;
import com.zx.framework.core.util.DatetimeUtils;
/**
 * 序列化和反序列化多日期格式
 * @author stylewolf
 * 2014-04-15
 */
public class GsonDateFormator implements JsonSerializer<Date>,JsonDeserializer<Date>{
	/**
	 * 默认日期解析格式
	 */
	public static final String[] DATE_FORMATS = new String[] {
        "yyyy-MM-dd HH:mm:ss",
        "yyyy-MM-dd",
        "yyyyMMdd",
        "MMyyyydd"
	};
	
	private String[] dateFormats = DATE_FORMATS;
	
    public String[] getDateFormats() {
		return dateFormats;
	}


	public void setDateFormats(String[] dateFormats) {
		this.dateFormats = dateFormats;
	}


	public GsonDateFormator(String[] dateFormats) {
		this.dateFormats = dateFormats;
	}

	public GsonDateFormator() {
	}
	@Override
    public Date deserialize(JsonElement jsonElement, Type typeOF,
            JsonDeserializationContext context)  {
        for (String format : dateFormats) {
            try {
                return DatetimeUtils.parseDate(jsonElement.getAsString(), format);
            } catch (ParseException e) {
            }
        }
        throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
                + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
    }


	@Override
	public JsonElement serialize(Date src, Type typeOfSrc,
			JsonSerializationContext context) {
		 for (String format : dateFormats) {
	            try {
	            	return context.serialize(DatetimeUtils.dateToString(src, format));
	            } catch (DateFormatException e) {
	            	
	            }
	      }
	      throw new JsonParseException("Unparseable date: \"" + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
	}
}
